package com.qfx.demo.handler;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.qfx.demo.vo.MessageBean;

/**
 * <h5>描述:全局错误信息处理</h5>
 * 实现了spring框架的ErrorController接口,执行完异常处理类之后执行此类
 */
//@RestController
public class MyErrorController implements ErrorController {
	
	/**
	 * 当发生异常时，会跳转到"/error"请求路径上
	 */
	@Override
	public String getErrorPath() {
		return "/error";
	}

	@RequestMapping("/error")
	public String handleError(HttpServletRequest request) {
		String message;
		// 获取statusCode:401,404,500
		Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
		if (statusCode == 400) {
			message = "语义有误,当前请求无法被服务器理解或请求参数有误!";
		} else if (statusCode == 401) {
			message = "当前请求需登录后访问!";
		} else if (statusCode == 403) {
			message = "权限不足!";
		} else if (statusCode == 404) {
			message = "请求的资源不存在!";
		} else {
			message = "系统不小心生病了,正在紧急修复中,请耐心等候...o(╥﹏╥)o";
		}
		
		MessageBean messageBean = new MessageBean();
		messageBean.setCode(statusCode.toString());
		messageBean.setMessage(message);
		return JSONObject.toJSONString(messageBean);
	}
}
